package com.shijie.filter.webFilter;

import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
@Order(1)
public class AuthorityFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 获取请求路径
        String path = request.getURI().getPath();
        // 判断是否存在并去除请求前缀"/api"
        if (path.startsWith("/api")) {
            path = path.replaceFirst("/api", "");
            request = request.mutate().path(path).build();
        }
        log.info("path:【{}】", path);

        // TODO 使用sa-token检查登录状态
        List<String> excludePaths = List.of("/client/register", "/client/checkCode",
                "/client/login", "/client/logout", "/client/resetPassword");
        boolean exclude = excludePaths.contains(path) || excludePaths.contains("/api" + path);
        if (!exclude) {
            String token = request.getHeaders().getFirst("sa-token");
            log.info("token:【{}】", token);
            boolean login = false;

            try {
                if (StringUtils.hasText(token)) {
                    String loginId = (String) StpUtil.getLoginIdByToken(token);
                    log.info("loginId:【{}】", loginId);
                    if (StringUtils.hasText(loginId)) {
                        login = StpUtil.isLogin(loginId);
                    }
                } else {
                    login = StpUtil.isLogin();
                }
            } catch (Exception e) {
                log.warn(e.toString());
            }

            if (login) {
                return chain.filter(exchange);
            }

            log.info("==== 未登录 ====");
            response.setStatusCode(HttpStatusCode.valueOf(401));

            /*DataBuffer buffer = response.bufferFactory().wrap("\"未登录\"".getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(buffer));*/
            return response.setComplete();
        }

        return chain.filter(exchange.mutate().request(request).build());
    }
}
